package com.dhecp.project.logstics.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.finance.domain.AccountCountForCompany;
import com.dhecp.project.finance.domain.AccountDetailedForCompany;
import com.dhecp.project.finance.mapper.AccountCountForCompanyMapper;
import com.dhecp.project.finance.mapper.AccountDetailedForCompanyMapper;
import com.dhecp.project.logstics.domain.FbaLogisticsPaymentEc;
import com.dhecp.project.logstics.domain.FbaLogisticsPaymentEcSon;
import com.dhecp.project.logstics.mapper.FbaLogisticsPaymentEcMapper;
import com.dhecp.project.logstics.mapper.FbaLogisticsPaymentEcSonMapper;
import com.dhecp.project.logstics.mapper.FbaLogisticsReconcileEcSonMapper;
import com.dhecp.project.logstics.service.FbaLogisticsPaymentEcService;
import com.dhecp.project.storage.enums.TailprogramEnum;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 物流二次付款单(FbaLogisticsPaymentEc表)服务实现类
 *
 * @author fxz
 * @since 2022-10-29 23:27:29
 */
@Service
public class FbaLgisticsPaymentEcServiceImpl extends BaseModuleServiceImpl implements FbaLogisticsPaymentEcService {
    @Autowired
    private FbaLogisticsPaymentEcMapper fbaLogisticsPaymentMapper;
    
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private FbaLogisticsPaymentEcSonMapper fbaLogisticsPaymentSonMapper;

    @Autowired
    private FbaLogisticsReconcileEcSonMapper fbaLogisticsReconcileEcSonMapper;

    @Autowired
    private AccountCountForCompanyMapper accountCountForCompanyMapper;

    @Autowired
    private AccountDetailedForCompanyMapper businessMapper;



    /**
     * 通过guid查询单条数据
     *
     * @param params 对象
     * @return 实例对象
     */
    @Override
    public FbaLogisticsPaymentEc queryFirstRecord(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return fbaLogisticsPaymentMapper.selectFirstRecordByNid(params);
    }


    /**
     * 通过guid查询单条数据
     *
     * @param params 对象
     * @return 实例对象
     */
    @Override
    public FbaLogisticsPaymentEc queryByBid(String bid) throws Exception{
        return fbaLogisticsPaymentMapper.selectByBid(bid);
    }

    /**
    * 查询列表数据
    */
    @Override
    public List<FbaLogisticsPaymentEc> queryList(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return fbaLogisticsPaymentMapper.select(params);
    }

    /**
    * 查询明细列表数据
    */
    @Override
    public List<FbaLogisticsPaymentEc> queryListSoList(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.code DESC";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }
        return fbaLogisticsPaymentMapper.querySoList(params);
    }

    @Override
    @Transactional
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new FbaLogisticsPaymentEc());
//        params.put("isAuto", false);
        AjaxResult ajaxResult = this.saveDataBase(params);

        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        String resNid = infoMap.get("nid").toString();

        FbaLogisticsPaymentEc fbaLogisticsPayment = JSON.parseObject(params.get("infoMap").toString(), FbaLogisticsPaymentEc.class);
        List<FbaLogisticsPaymentEcSon> onSonData = new ArrayList<>();
        if (params.containsKey("sonData")){
            onSonData = JSON.parseArray(params.get("infoItems").toString(), FbaLogisticsPaymentEcSon.class);
        }

        List<RecordCheck> guidMapList = fbaLogisticsPaymentMapper.findRecords(resNid);

        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()){
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList){
                if (recordCheck != null && recordCheck.getGuid() != null){
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }
        if (onSonData == null || onSonData.size() == 0){
            resNid = "0";
        }else{
            resNid = infoMap.get("nid").toString();
            String guid = "";
            if (fbaLogisticsPayment.getGuid() == null){
                guid = RandomValueUtils.getGUID();
                fbaLogisticsPayment.setGuid(guid);
            }else{
                guid = fbaLogisticsPayment.getGuid().toString();
            }

            for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                Object fieldValue = infoMap.get(field);
                ReflectUtils.setValue(fbaLogisticsPayment, field, fieldValue);
            }

            BigDecimal money = BigDecimal.ZERO;
            for (FbaLogisticsPaymentEcSon item : onSonData
            ) {
                //二次付款金额
                money = money.add(item.getLogisticsFeesDz());
            }

            if (guidMap.get(guid) == null){
                fbaLogisticsPayment.setCode(fbaLogisticsPayment.getBid());
                fbaLogisticsPaymentMapper.insert(fbaLogisticsPayment);
            }else{
                fbaLogisticsPayment.setLogisticsFeesFkTol(String.valueOf(money.subtract(new BigDecimal(fbaLogisticsPayment.getAmountCredit()))));
                fbaLogisticsPaymentMapper.update(fbaLogisticsPayment);
                guidMap.remove(guid);
            }
            List<FbaLogisticsPaymentEcSon> lodData = fbaLogisticsPaymentSonMapper.queryListCode(fbaLogisticsPayment.getCode());
            if (lodData.size()>0){
                for (FbaLogisticsPaymentEcSon item : lodData
                ) {
                    fbaLogisticsPaymentSonMapper.delete(item);
                    fbaLogisticsReconcileEcSonMapper.updateByStateName(item.getCodeFbaLogsticsOrder(), TailprogramEnum.StateName.HAVERECONCILED.value);
                }
            }


            for (FbaLogisticsPaymentEcSon item : onSonData
            ) {
                item.setGuid(RandomValueUtils.getGUID());
                item.setCreatetime(new Date());
                item.setCodePaymentEc(fbaLogisticsPayment.getCode());
                item.setCreateuser(fbaLogisticsPayment.getbUser());
                fbaLogisticsPaymentSonMapper.insert(item);
                fbaLogisticsReconcileEcSonMapper.updateByStateName(item.getCodeFbaLogsticsOrder(), TailprogramEnum.StateName.DURINGPAYMENT.value);
            }

        }


        if (!guidMap.isEmpty()){
            for (String guid : guidMap.keySet()){
                List<FbaLogisticsPaymentEcSon> lodData = fbaLogisticsPaymentSonMapper.queryListCode(fbaLogisticsPayment.getCode());
                fbaLogisticsPaymentSonMapper.deleteCodePaymentEc(fbaLogisticsPayment.getCode());
                fbaLogisticsPaymentMapper.delete(guid);
                for (FbaLogisticsPaymentEcSon fbaLogisticsPaymentSon : lodData){
                    fbaLogisticsReconcileEcSonMapper.updateByStateName(fbaLogisticsPaymentSon.getCodeFbaLogsticsOrder(), TailprogramEnum.StateName.HAVERECONCILED.value);
                }
            }
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }

    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == ""){
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = fbaLogisticsPaymentMapper.selectLastNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = fbaLogisticsPaymentMapper.selectNextNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }

    /**
     *@Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<FbaLogisticsPaymentEc> businessDataList = fbaLogisticsPaymentMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        List<AccountDetailedForCompany> accountList =new ArrayList<>();
        List<AccountCountForCompany> accountCountForCompanyList =new ArrayList<>();
        AccountCountForCompany accountCountForCompany;
        for (FbaLogisticsPaymentEc businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            fbaLogisticsPaymentMapper.updateFlow(updateFlow);
            //                     物流公司渠道
            AccountCountForCompany logisticsQdAccount = accountCountForCompanyMapper.queryFirstByVGsBm(businessData.getCodeCompany());
            if (logisticsQdAccount == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("物流渠道实时资金不存在,请核实后再操作!");
            }
            accountCountForCompany = accountCountForCompanyMapper.queryFirstByVGsBm(logisticsQdAccount.getvGsBm());

            if (updateFlow.getActiveFlow().equals("end")) {
                //查询详情信息
                List<FbaLogisticsPaymentEcSon> fbaLogisticsPaymentSonList = fbaLogisticsPaymentSonMapper.queryListCode(businessData.getCode());
                for (FbaLogisticsPaymentEcSon fbaLogisticsPaymentSon : fbaLogisticsPaymentSonList) {
                    fbaLogisticsReconcileEcSonMapper.updateByStateName(fbaLogisticsPaymentSon.getCodeFbaLogsticsOrder(), TailprogramEnum.StateName.ACCOUNTPAID.value);
                    //资金流水(从物流部对应的渠道账户支出到物流合作商)
                    AccountDetailedForCompany account = new AccountDetailedForCompany();
                    account.setGuid(RandomValueUtils.getGUID());
                    account.setvGsBm(logisticsQdAccount.getvGsBm());
                    account.setvGsMc(logisticsQdAccount.getvGsMc());
                    account.setvGsJc(logisticsQdAccount.getvGsJc());
                    account.setvGsBmP(businessData.getPartnerId());
                    account.setvGsMcP(businessData.getPartnerName());
                    account.setvGsJcP(businessData.getPartnerName());
                    account.setvJyLx("物流服务→头程运费支出");
                    account.setfJe(-Double.valueOf(fbaLogisticsPaymentSon.getLogisticsFeesDz().toString()));
                    account.setdJySj(fbaLogisticsPaymentSon.getCreatetime());
                    Date shsj = new Date();
                    account.setdShSj(shsj);
                    account.setvBz("物流二次付款单号:" + businessData.getCode() + ",物流二次对账单号:" + fbaLogisticsPaymentSon.getCodereconcileEc() + "，运单号:" + fbaLogisticsPaymentSon.getWaybillNumber() + "，物流订单号:" + fbaLogisticsPaymentSon.getCodeFbaLogsticsOrder());
                    account.setCreateTime(new Date());
                    account.setWriteTime((businessData.getWriteTime()!=null?businessData.getWriteTime():shsj));
                    accountList.add(account);

                    //扣减金额
                    accountCountForCompany.setfJe(accountCountForCompany.getfJe() - Double.valueOf(String.valueOf(fbaLogisticsPaymentSon.getLogisticsFeesDz())));
                }
                if (!businessData.getAmountCredit().equals("0")) {
                    //抵扣金额
                    AccountDetailedForCompany account = new AccountDetailedForCompany();
                    account.setGuid(RandomValueUtils.getGUID());
                    account.setvGsBm(logisticsQdAccount.getvGsBm());
                    account.setvGsMc(logisticsQdAccount.getvGsMc());
                    account.setvGsJc(logisticsQdAccount.getvGsJc());
                    account.setvGsBmP(businessData.getPartnerId());
                    account.setvGsMcP(businessData.getPartnerName());
                    account.setvGsJcP(businessData.getPartnerName());
                    account.setvJyLx("物流服务→头程运费支出");
                    account.setfJe(Double.valueOf(businessData.getAmountCredit()));
                    account.setdJySj(businessData.getCreateTime());
                    account.setdShSj(new Date());
                    account.setvBz("抵款:" + businessData.getAmountCredit() + ",物流二次付款单号:" + businessData.getCode());
                    account.setCreateTime(new Date());
                    account.setWriteTime(businessData.getWriteTime());
                    accountList.add(account);

                    //扣减金额
                    accountCountForCompany.setfJe(accountCountForCompany.getfJe() + Double.valueOf(businessData.getAmountCredit()));
                    accountCountForCompanyList.add(accountCountForCompany);
                }
            }
        }
        //创建临时表 -  新增流水 - 删除临时表 （必须同时新增临时表才能跳过资金的判断）
        int insertLength = accountList.size();
        int i = 0;
        while (insertLength > 50) {
            businessMapper.insertBatchNew(accountList.subList(i, i + 50));

            i = i + 50;
            insertLength = insertLength - 50;
        }
        if (insertLength > 0) {
            businessMapper.insertBatchNew(accountList.subList(i, i + insertLength));
        }

        int accountCountiInsertLength = accountCountForCompanyList.size();
        int j = 0;
        while (accountCountiInsertLength > 50) {
            accountCountForCompanyMapper.updateAccountCountForCompanyBatch(accountCountForCompanyList.subList(j, j + 50));

            j = j + 50;
            accountCountiInsertLength = accountCountiInsertLength - 50;
        }
        if (accountCountiInsertLength > 0) {
            //扣减金额
            accountCountForCompanyMapper.updateAccountCountForCompanyBatch(accountCountForCompanyList.subList(j, j + accountCountiInsertLength));
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     *@Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<FbaLogisticsPaymentEc> businessDataList = fbaLogisticsPaymentMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        List<AccountDetailedForCompany> accountList =new ArrayList<>();
        List<AccountCountForCompany> accountCountForCompanyList =new ArrayList<>();
        AccountCountForCompany accountCountForCompany;
        for (FbaLogisticsPaymentEc businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            fbaLogisticsPaymentMapper.updateFlow(updateFlow);

            //                     物流公司渠道
            AccountCountForCompany logisticsQdAccount = accountCountForCompanyMapper.queryFirstByVGsBm(businessData.getCodeCompany());
            if (logisticsQdAccount == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("物流渠道实时资金不存在,请核实后再操作!");
            }
            accountCountForCompany = accountCountForCompanyMapper.queryFirstByVGsBm(logisticsQdAccount.getvGsBm());

            if (infoMap.get("activeFlow").equals("end")) {
                //查询详情信息
                List<FbaLogisticsPaymentEcSon> fbaLogisticsPaymentSonList = fbaLogisticsPaymentSonMapper.queryListCode(businessData.getCode());
                for (FbaLogisticsPaymentEcSon fbaLogisticsPaymentSon : fbaLogisticsPaymentSonList) {
                    fbaLogisticsReconcileEcSonMapper.updateByStateName(fbaLogisticsPaymentSon.getCodeFbaLogsticsOrder(), TailprogramEnum.StateName.DURINGPAYMENT.value);
                    //资金流水(从物流部对应的渠道账户支出到物流合作商)
                    AccountDetailedForCompany account = new AccountDetailedForCompany();
                    account.setGuid(RandomValueUtils.getGUID());
                    account.setvGsBm(logisticsQdAccount.getvGsBm());
                    account.setvGsMc(logisticsQdAccount.getvGsMc());
                    account.setvGsJc(logisticsQdAccount.getvGsJc());
                    account.setvGsBmP(businessData.getPartnerId());
                    account.setvGsMcP(businessData.getPartnerName());
                    account.setvGsJcP(businessData.getPartnerName());
                    account.setvJyLx("物流服务→头程运费支出");
                    account.setfJe(Double.valueOf(fbaLogisticsPaymentSon.getLogisticsFeesDz().toString()));
                    account.setdJySj(fbaLogisticsPaymentSon.getCreatetime());
                    Date shsj = new Date();
                    account.setdShSj(shsj);
                    account.setWriteTime((businessData.getWriteTime()!=null?businessData.getWriteTime():shsj));
                    account.setvBz("(退回)物流二次付款单号:" + businessData.getCode() + ",物流二次对账单号:" + fbaLogisticsPaymentSon.getCodereconcileEc() + "，运单号:" + fbaLogisticsPaymentSon.getWaybillNumber() + "，物流订单号:" + fbaLogisticsPaymentSon.getCodeFbaLogsticsOrder());
                    account.setCreateTime(new Date());
                    accountList.add(account);

                    //扣减金额
                    accountCountForCompany.setfJe(accountCountForCompany.getfJe() + Double.valueOf(String.valueOf(fbaLogisticsPaymentSon.getLogisticsFeesDz())));
                }
                if (!businessData.getAmountCredit().equals("0")) {
                    //抵扣金额
                    AccountDetailedForCompany account = new AccountDetailedForCompany();
                    account.setGuid(RandomValueUtils.getGUID());
                    account.setvGsBm(logisticsQdAccount.getvGsBm());
                    account.setvGsMc(logisticsQdAccount.getvGsMc());
                    account.setvGsJc(logisticsQdAccount.getvGsJc());
                    account.setvGsBmP(businessData.getPartnerId());
                    account.setvGsMcP(businessData.getPartnerName());
                    account.setvGsJcP(businessData.getPartnerName());
                    account.setvJyLx("物流服务→头程运费支出");
                    account.setfJe(-Double.valueOf(businessData.getAmountCredit()));
                    account.setdJySj(businessData.getCreateTime());
                    account.setdShSj(new Date());
                    account.setvBz("(退回)抵款:" + businessData.getAmountCredit() + ",物流二次付款单号:" + businessData.getCode());
                    account.setCreateTime(new Date());
                    accountList.add(account);

                    //扣减金额
                    accountCountForCompany.setfJe(accountCountForCompany.getfJe() - Double.valueOf(businessData.getAmountCredit()));
                    accountCountForCompanyList.add(accountCountForCompany);
                }
            }
        }
        //创建临时表 -  新增流水 - 删除临时表 （必须同时新增临时表才能跳过资金的判断）
        int insertLength = accountList.size();
        int i = 0;
        while (insertLength > 50) {
            businessMapper.insertBatchNew(accountList.subList(i, i + 50));

            i = i + 50;
            insertLength = insertLength - 50;
        }
        if (insertLength > 0) {
            businessMapper.insertBatchNew(accountList.subList(i, i + insertLength));
        }

        int accountCountiInsertLength = accountCountForCompanyList.size();
        int j = 0;
        while (accountCountiInsertLength > 50) {
            accountCountForCompanyMapper.updateAccountCountForCompanyBatch(accountCountForCompanyList.subList(j, j + 50));

            j = j + 50;
            accountCountiInsertLength = accountCountiInsertLength - 50;
        }
        if (accountCountiInsertLength > 0) {
            //扣减金额
            accountCountForCompanyMapper.updateAccountCountForCompanyBatch(accountCountForCompanyList.subList(j, j + accountCountiInsertLength));
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * 修改记账时间
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateWriteTime(Map<String, Object> params) {
        List<FbaLogisticsPaymentEc> businessDataList = JSON.parseArray(params.get("infoItems").toString(), FbaLogisticsPaymentEc.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (FbaLogisticsPaymentEc businessData : businessDataList) {
            fbaLogisticsPaymentMapper.updateWriteTime(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

}

